package com.game;

import java.util.ArrayList;

import com.card.Card;
import com.card.CardDeck;
import com.user.Player;

public class Dealer 
{
	private CardDeck cardDeck = null;
	private ArrayList<Player> playerList = null;

	public Dealer()
	{
		this.cardDeck = new CardDeck();
		this.playerList = new ArrayList<Player>();
	}
	
	public void acceptPlayer(Player player)
	{
		this.playerList.add(player);
	}
	
	public void goBetting()
	{
		for(int i = 0, size = this.playerList.size(); i < size; i++)
		{
			this.playerList.get(i).bet();
		}
	}
	
	public void goCut()
	{
		for(int i = 0, size = this.playerList.size(); i < size; i++)
		{
			this.playerList.get(i).cut(this.cardDeck);
		}		
	}
	
	public void assignCards()
	{
		for(int i = 0, size = this.playerList.size(); i < size; i++)
		{
			this.playerList.get(i).getCardSetFrom(this.cardDeck);
		}
	}
	
	public void collectCards()
	{
		for(int i = 0, size = this.playerList.size(); i < size; i++)
		{
			this.playerList.get(i).returnCardSetTo(this.cardDeck);
		}		
	}
	
	public Player judgeWinner()
	{
		int maxScore = Integer.MIN_VALUE;
		
		Player winner = null;
		Player player = null;
		
		for(int i = 0, size = this.playerList.size(); i < size; i++)
		{
			player = this.playerList.get(i);
					
			if(this.calScore(player)>maxScore)
			{
				winner = player;
			}
		}

		return winner;
	}
	
	private int calScore(Player player)
	{
		int cardDuplicateCount = 0, maxCardDuplicateCount = Integer.MIN_VALUE;
		int lowestNumber = Integer.MAX_VALUE;
		Card[] cardSet = player.getCardSet();
		
		for(int i = 0; i < cardSet.length; i++)
		{
			cardDuplicateCount = 0;
			
			for(int j = i+1; j < cardSet.length; j++)
			{
				if(cardSet[i].getShapeValue() == cardSet[j].getShapeValue())
				{
					cardDuplicateCount++;
				}
			}
			
			if(cardDuplicateCount > maxCardDuplicateCount)
			{
				maxCardDuplicateCount = cardDuplicateCount;
			}
			
			if(cardSet[i].getNumberValue() < lowestNumber)
			{
				lowestNumber = cardSet[i].getNumberValue();
			}
		}
		
		return (maxCardDuplicateCount*100)+lowestNumber;
	}
	
	public Player getWinner(ArrayList<Player> playerList)
	{
		int maxScore = Integer.MIN_VALUE;
		
		Player winner = null;
		Player player = null;
		
		for(int i = 0, size = playerList.size(); i < size; i++)
		{
			player = playerList.get(i);
					
			if(this.calScore(player)>maxScore)
			{
				winner = player;
			}
		}

		return winner;
	}

}